package ContentServer;

import com.alibaba.fastjson.JSONObject;
import com.sun.net.httpserver.HttpServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public class ContentServer {
    private String filePath;
    private String host;
    private Integer serverId;

    public ContentServer(String host, String filePath) {
        this.host = host;
        this.filePath = filePath;
        this.serverId = (int)(Math.random()*1000);
    }

    public void sendPutRequest() throws IOException {

// construct JSON data
        List<JSONObject> jsonObjects = DataParser.parseFile(filePath);

// construct http PUT request

        for (JSONObject item : jsonObjects) {
            item.remove("timestamp");
            item.put("timestamp",System.currentTimeMillis());
            item.put("serverId",serverId);
            int port = Integer.parseInt(host.split(":")[1]);
            String server = host.split(":")[0];
            Socket socket = new Socket(server, port);
            String request = "PUT /putData HTTP/1.1\r\n" +
                    "Host: " + host + "\r\n" +
                    "Content-Type: application/json\r\n" +
                    "Content-Length: " + item.toString().length() + "\r\n" +
                    "\r\n" +
                    item;

// send PUT request
            OutputStream out = socket.getOutputStream();
            out.write(request.getBytes());

// get response
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                // deal with response
            }
// close resource
            out.close();
            in.close();
            socket.close();
        }
    }

    public void run() {
        while (true) {
            try {
                sendPutRequest();
                Thread.sleep(3000); // wait for 3 sec
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception{
        JSONObject json = new JSONObject();
        json.put("name", "bob");
        if (args.length < 2) {
            System.out.println("Usage: java ContentServer <server:port> <file_path>");
            return;
        }
        String host = args[0];
        String filePath = args[1];
        new ContentServer(host,filePath).run();
    }
}
